package org.hank.compose_yyzs.ui.screen

import android.app.Activity
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.os.LocaleListCompat
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.ui.destinations.TipsDialogDestination
import org.hank.compose_yyzs.ui.destinations.UploadFileScreenDestination
import org.hank.compose_yyzs.ui.destinations.UserInfoScreenDestination
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.ui.widget.dialog.BottomListSelectDialog
import org.hank.compose_yyzs.ui.widget.dialog.BottomWifiSettingDialog
import org.hank.compose_yyzs.ui.widget.dialog.TipsDialog
import org.hank.compose_yyzs.utils.getString
import org.hank.compose_yyzs.utils.getStringArray
import org.hank.compose_yyzs.utils.getStringGlobal
import org.hank.compose_yyzs.viewmodel.SettingViewEvent
import org.hank.compose_yyzs.viewmodel.SettingViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/6/5 9:18
 *描述:
 */

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Destination
@Composable
fun SettingScreen(
    navigation: DestinationsNavigator
) {
    var viewModel: SettingViewModel = hiltViewModel()
    var testerName = viewModel.testerName.collectAsStateWithLifecycle()
    var customerName = viewModel.customerName.collectAsStateWithLifecycle()
    var currentWifiAddress = viewModel.currentWifiAddress.collectAsStateWithLifecycle()
    var currentCache = viewModel.cache.collectAsStateWithLifecycle()
    var showTips = viewModel.showTips.collectAsStateWithLifecycle()
    var showTipsContent = viewModel.showTipsContent.collectAsStateWithLifecycle()
    var talentName = viewModel.telantName.collectAsStateWithLifecycle()
    var isShowSetting = remember { mutableStateOf(false) }
    var scope = rememberCoroutineScope()
    var showLanguage = remember{ mutableStateOf(false) }
    var lifecycleOwner = LocalLifecycleOwner.current
    var context = LocalContext.current

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_CREATE) {
                viewModel.getCache(context)
                //获取用户信息
                viewModel.getUserInfo()
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    LaunchedEffect(Unit) {
        viewModel.viewEvents.collect {
            if (it is SettingViewEvent.ClearCacheSuccess) {
                navigation.navigate(TipsDialogDestination(getStringGlobal(R.string.clear_cache_ret)))
            }
            if (it is SettingViewEvent.ErrorMessage) {
                navigation.navigate(TipsDialogDestination(it.message))
            }
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        Surface(shadowElevation = 0.5.dp) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(color = AppTheme.colors.mainColor)
            ) {
                Text(
                    getString(R.string.main_menu_setting),
                    modifier = Modifier
                        .align(Alignment.CenterHorizontally)
                        .padding(top = 16.dp, bottom = 16.dp),
                    style = MaterialTheme.typography.titleLarge
                )
                Divider(color = AppTheme.colors.divider, thickness = 1.dp)

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 16.dp, end = 16.dp, top = 16.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .combinedClickable {
                                navigation.navigate(UserInfoScreenDestination.route)
                            }
                            .padding(16.dp), verticalAlignment = Alignment.CenterVertically

                    ) {

                        Box(modifier = Modifier.width(40.dp)) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_tester),
                                contentDescription = "",
                                modifier = Modifier.align(
                                    Alignment.Center
                                )
                            )
                        }
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = getString(R.string.setting_tester),
                            modifier = Modifier.weight(1f)
                        )
                        if (!testerName.value.isNullOrEmpty())
                            Text(
                                text = testerName.value,
                                style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary)
                            )
                        Spacer(modifier = Modifier.width(8.dp))
                        Image(
                            painter = painterResource(id = R.mipmap.ic_into_grey),
                            contentDescription = ""
                        )
                    }
                    Divider(color = AppTheme.colors.divider, thickness = 1.dp)

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                navigation.navigate(UploadFileScreenDestination.route)
                            }
                            .padding(16.dp), verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(modifier = Modifier.width(40.dp)) {
                            Image(
                                painter = painterResource(id = R.drawable.ic_upload),
                                contentDescription = "",
                                modifier = Modifier.align(
                                    Alignment.Center
                                )
                            )
                        }
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = getString(R.string.setting_file),
                            modifier = Modifier.weight(1f)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Image(
                            painter = painterResource(id = R.mipmap.ic_into_grey),
                            contentDescription = ""
                        )
                    }
                    Divider(color = AppTheme.colors.divider, thickness = 1.dp)

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp), verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(modifier = Modifier.width(40.dp)) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_customer),
                                contentDescription = "",
                                modifier = Modifier.align(
                                    Alignment.Center
                                )
                            )
                        }
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = getString(R.string.setting_customer),
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        if (!talentName.value.isNullOrEmpty())
                            Text(
                                modifier = Modifier.weight(1f),
                                text = talentName.value,
                                style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary),
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                        Spacer(modifier = Modifier.width(8.dp))
                    }
                    Divider(color = AppTheme.colors.divider, thickness = 1.dp)

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                isShowSetting.value = !isShowSetting.value
                            }
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(modifier = Modifier.width(40.dp)) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_connect_wifi),
                                contentDescription = "",
                                modifier = Modifier.align(
                                    Alignment.Center
                                )
                            )
                        }
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = getString(R.string.setting_wifi),
                            modifier = Modifier.weight(1f)
                        )
                        if (currentWifiAddress.value.isNotEmpty())
                            Text(
                                text = currentWifiAddress.value,
                                style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary)
                            )
                        Spacer(modifier = Modifier.width(8.dp))
                        Image(
                            painter = painterResource(id = R.mipmap.ic_into_grey),
                            contentDescription = ""
                        )
                    }
                    Divider(color = AppTheme.colors.divider, thickness = 1.dp)

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                scope.launch {
                                    showLanguage.value = true
                                }
                            }
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(modifier = Modifier.width(40.dp)) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_language),
                                contentDescription = "",
                                modifier = Modifier.align(
                                    Alignment.Center
                                )
                            )
                        }
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = getString(R.string.setting_change_language),
                            modifier = Modifier.weight(1f)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Image(
                            painter = painterResource(id = R.mipmap.ic_into_grey),
                            contentDescription = ""
                        )
                    }
                    Divider(color = AppTheme.colors.divider, thickness = 1.dp)

                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable {
                                scope.launch {
                                    viewModel.showTipsContent.emit(getStringGlobal(R.string.clear_cache_tips))
                                    viewModel.tipsConfirm = { viewModel.clearCache() }
                                    viewModel.showTips.emit(true)
                                }
                            }
                            .padding(16.dp), verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(modifier = Modifier.width(40.dp)) {
                            Image(
                                painter = painterResource(id = R.mipmap.ic_cache),
                                contentDescription = "",
                                modifier = Modifier.align(
                                    Alignment.Center
                                )
                            )
                        }
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = getString(R.string.setting_clear_cache),
                            modifier = Modifier.weight(1f)
                        )
                        if (!currentCache.value.isNullOrEmpty())
                            Text(
                                text = "${currentCache.value}M",
                                style = MaterialTheme.typography.bodyMedium.copy(color = AppTheme.colors.textSecondary)
                            )
                        Spacer(modifier = Modifier.width(8.dp))
                        Image(
                            painter = painterResource(id = R.mipmap.ic_into_grey),
                            contentDescription = ""
                        )
                    }
                }

            }

            if (showTips.value) {
                TipsDialog(
                    tipsString = showTipsContent.value,
                    isCancelAble = true,
                    {
                        scope.launch { viewModel.showTips.emit(false) }
                    },
                    {
                        viewModel.tipsConfirm.invoke()
                    })
            }
        }

        Spacer(modifier = Modifier.height(36.dp))

        Button(
            onClick = {
                scope.launch {
                    viewModel.showTipsContent.emit(getStringGlobal(R.string.setting_logout_confirm))
                    viewModel.tipsConfirm = { navigation.popBackStack() }
                    viewModel.showTips.emit(true)
                }
            },
            colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.background),
            border = BorderStroke(1.dp, AppTheme.colors.divider),
            shape = MaterialTheme.shapes.large,
            modifier = Modifier.align(CenterHorizontally)
        ) {
            Text(
                text = getString(R.string.setting_logout),
                modifier = Modifier.padding(start = 36.dp, end = 36.dp),
                style = MaterialTheme.typography.bodyLarge.copy(color = AppTheme.colors.textSecondary)
            )
        }

        BottomWifiSettingDialog(isShowSetting, navigation, {
            scope.launch(Dispatchers.IO) {
                viewModel.updateCurrentWifi()
            }
        }) {
            isShowSetting.value = false
        }

        BottomListSelectDialog(
            title = getString(resourceId = R.string.setting_change_language),
            state = showLanguage,
            listItems = getStringArray(resourceId = R.array.language_list).toList(),
            navigator = navigation,
            onItemClick = {
                scope.launch {
                    showLanguage.value = false
                    AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(if (it == 0) "zh" else "en"))
                    (context as Activity).recreate()
                }
            }
        ) {

            scope.launch {
                showLanguage.value = false
            }
        }
    }
}